<template>
  <div>
    <el-dialog :title="id == null ? '用户添加' : '用户编辑'" :visible.sync="visible" :loading="true" :close-on-click-modal="false">

      <el-form ref="main-form" status-icon :model="mainQuery" :rules="rules" label-width="130px" label-position="left" :inline="false" style="width: 450px;">
        <!-- <el-form-item label="用户ID" size="mini" v-if="id != null">
          <el-input placeholder="" onfocus="this.select()" v-model="id" readonly></el-input>
        </el-form-item> -->
        <el-form-item label="用户名" size="mini" prop="username">
          <el-input placeholder="" v-model="mainQuery.username" @keyup.enter.native="submit" :readonly="!!id" :disabled="loading" clearable></el-input>
        </el-form-item>

        <template v-if="resetPassword || id == null">
          <el-form-item label="密码" size="mini" prop="password">
            <el-input placeholder="" type="password" v-model="mainQuery.password" @keyup.enter.native="submit" :disabled="loading" clearable></el-input>
          </el-form-item>
          <el-form-item label="确认密码" size="mini" prop="password_confirmation">
            <el-input placeholder="" type="password" v-model="mainQuery.password_confirmation" @keyup.enter.native="submit" :disabled="loading" clearable></el-input>
          </el-form-item>
        </template>

        <el-form-item size="mini" v-if="id != null">
          <el-button v-if="!resetPassword" @click="handleResetPassword" type="warning" :disabled="loading">重置密码</el-button>
          <el-button v-else @click="handleResetPassword" :disabled="loading">取消</el-button>
        </el-form-item>

        <el-form-item size="mini" v-if="id != null" label="Google验证码密钥">
          <el-button @click="handleResetGoogleAuthSecret" type="primary" :disabled="loading">重置</el-button>
          <el-button @click="handleViewGoogleAuthSecret" v-if="!isViewingGoogleAuthSecret">查看</el-button>
          <el-input style="width: 180px; margin: 0 10px;" ref="googleAuthSecret" v-model="mainQuery.googleAuthSecret" readonly v-if="isViewingGoogleAuthSecret"></el-input>
          <el-link type="primary" @click="copyData('googleAuthSecret', mainQuery.googleAuthSecret)" v-if="isViewingGoogleAuthSecret">复制</el-link>
        </el-form-item>

        <el-form-item label="真实姓名" size="mini" prop="realName">
          <el-input placeholder="" v-model="mainQuery.realName" @keyup.enter.native="submit" clearable :disabled="loading"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" size="mini" prop="mobile">
          <el-input placeholder="" v-model="mainQuery.mobile" @keyup.enter.native="submit" clearable :disabled="loading"></el-input>
        </el-form-item>
        <el-form-item label="Email" size="mini" prop="email">
          <el-input placeholder="" v-model="mainQuery.email" @keyup.enter.native="submit" clearable :disabled="loading"></el-input>
        </el-form-item>
        <el-form-item label="用户角色" size="mini" prop="roleId" v-if="!hideRole">
          <el-select v-model="mainQuery.roleId" placeholder="未选择" clearable :disabled="loading">
            <el-option v-for="item in roleOptions" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="销售级别" size="mini" prop="level" v-if="showLevelOptions">
          <el-select v-model="mainQuery.level" placeholder="未选择" :disabled="loading">
            <el-option v-for="item in levelOptions" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="销售上级" size="mini" prop="level" v-if="showLevelOptions && mainQuery.level == 2">
          <el-select v-model="mainQuery.parentId" placeholder="未选择" :disabled="loading">
            <el-option v-for="item in salesLeve1Options" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="关联商户(多选)" size="mini" prop="mchIdList" v-if="!hideMch">
          <el-select v-model="mainQuery.mchIdList" filterable remote reserve-keyword multiple placeholder="请输入关键词" :remote-method="fetchMchOptions">
            <el-option v-for="item in mchOptions" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="用户状态" size="mini" prop="status">
          <el-select v-model="mainQuery.status" placeholder="未选择" :disabled="loading">
            <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间" size="mini" v-if="data != null">
          <el-input placeholder="" v-model="data.createTime" readonly></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">

        <!-- <el-popover
          v-if="id != null"
          placement="top"
          width="160"
          v-model="popDeleteVisible">
          <p>确定删除吗？</p>
          <div style="text-align: right; margin: 0">
            <el-button size="mini" type="default" @click="popDeleteVisible = false">取消</el-button>
            <el-button type="danger" size="mini" @click="submitDel">确定</el-button>
          </div>
          <el-button type="danger" slot="reference"  size="small" style="float: left;" :loading="loading">删 除</el-button>
        </el-popover> -->

        <el-button @click="close" size="mini">取 消</el-button>
        <el-button @click="submit" size="mini" type="primary" :loading="loading">提 交</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>

import ApiMain from '@/api/system.member';
import ApiMch from '@/api/mch.info';
import { mapState, mapActions } from 'vuex'

export default {
  mixins: [
  ],
  props: [
    'statusOptions',
    'roleOptions',
    'hideRole',
    'isSales',
    'hideMch'
  ],
  data() {
    return {

      visible: false,
      popDeleteVisible: false,
      loading: false,
      mchLoading: false,

      mchOptions: [],

      mainQueryRaw: null,
      mainQuery: {
        username: '',
        password: '',
        password_confirmation: '',
        nick: '',
        realName: '',
        email: '',
        mobile: '',
        roleId: '',
        mchIdList: [],
        level: 1,
        parentId: '',
        status: 1,
      },

      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 4, max: 99, message: '长度在 4 到 99 个字符', trigger: 'blur' }
        ],
        nick: [
          { required: true, message: '请输入昵称', trigger: 'blur' },
        ],
        realName: [
          { required: true, message: '请输入真实姓名', trigger: 'blur' },
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
        ],
        roleId: [
          { required: true, message: '请选择用户角色', trigger: 'blur' },
        ],
        mobile: [
          { required: true, message: '请输入手机', trigger: 'blur' },
        ],

        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
        ],


        password_confirmation: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (value !== this.mainQuery.password) {
                callback(new Error('两次输入密码不一致'));
              }
              else {
                callback();
              }
            },
            trigger: 'blur'
          },
        ],
      },

      id: null,
      data: null,
      resetPassword: false,
      isViewingGoogleAuthSecret: false,

      showLevelOptions: false,
      levelOptions: [
        { label: '一级', value: 1 },
        { label: '二级', value: 2 },
      ],
      salesLeve1Options: [],
    }
  },
  mounted() {
    this.mainQueryRaw = Object.copy(this.mainQuery);
  },

  watch: {
    'mainQuery.roleId'(newVal) {
      this.showLevelOptions = false;
      for (let i in this.roleOptions) {
        if (newVal == this.roleOptions[i].value && this.roleOptions[i].extraType == 1) {
          this.showLevelOptions = true;
          this.fetchSalesOptions();
          this.hideMch = true;
          this.mainQuery.mchIdList = [];
        }
      }
      // 不是销售角色
      if (!this.showLevelOptions) {
        this.hideMch = false;
      }
    },

    'mainQuery.level'(newVal) {
      if (newVal == 1) {
        this.mainQuery.parentId = '';
      }
    }
  },

  methods: {

    ...mapActions('d2admin/account', [
      'logout'
    ]),

    show(id = null) {

      this.reset();
      if (id) {
        this.id = id;
        this.fetchData();
      }
      this.fetchMchOptions();
      this.visible = true;
    },

    close() {
      this.visible = false;
      this.$emit('dialog-close');
    },

    reset() {
      this.mainQuery = {
        username: '',
        password: '',
        password_confirmation: '',
        nick: '',
        realName: '',
        email: '',
        mobile: '',
        roleId: '',
        mchIdList: [],
        level: 1,
        parentId: '',
        status: 1,
      }
      console.log(this.$refs)
      // this.mainQuery = Object.copy(this.mainQueryRaw);
      if (this.$refs['main-form']) {
        this.$nextTick(() => {
          try {
            this.$refs['main-form'].resetFields();
          } catch (error) {
          }
        });
      }
      this.id = null;
      this.data = null;
      this.resetPassword = false;
      this.isViewingGoogleAuthSecret = false;
    },

    handleResetPassword() {
      this.resetPassword = !this.resetPassword;
    },

    // 重置GoogleAuthSecret
    handleResetGoogleAuthSecret() {
      this.$confirm('确定要重置Google验证码密钥吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        ApiMain.resetGoogleAuthSecret({ id: this.id }).then((data) => {
          console.log(data)
          this.$message({ message: '操作成功', type: 'success' });
          this.fetchData();
        });
      });
    },

    // 查看GoogleAuthSecret
    handleViewGoogleAuthSecret() {
      this.isViewingGoogleAuthSecret = true
    },

    async fetchData() {

      this.loading = true;

      try {
        var re = await ApiMain.info({ id: this.id });

        this.data = re;
      } catch (err) {
        this.data = null;
      }

      this.renderData();

      this.loading = false;
    },

    fetchMchOptions(search, id) {
      this.mchLoading = true;
      ApiMch.option({ search: search, id: id ? id : '', notOtherSalesRelate: this.isSales ? 1 : 0, adminId: this.isSales ? this.id : '' }).then(re => {
        this.mchOptions = re
        this.mchLoading = false
      })
    },

    fetchSalesOptions() {
      ApiMain.getOption({ level: 1, roleId: this.mainQuery.roleId }).then(re => {
        this.salesLeve1Options = re
      })
    },

    renderData() {

      this.mainQuery.username = this.data.username;
      this.mainQuery.realName = this.data.realName;
      this.mainQuery.nick = this.data.nick;
      this.mainQuery.email = this.data.email;
      this.mainQuery.mobile = this.data.mobile;
      this.mainQuery.roleId = this.data.roleId;
      this.mainQuery.googleAuthSecret = this.data.googleAuthSecret;
      this.mainQuery.mchIdList = this.data.mchIdList;
      this.mainQuery.status = this.data.status;
      this.mainQuery.level = this.data.level;
      this.mainQuery.parentId = this.data.parentId;

      // this.fetchMchOptions('', this.data.mchIdList);

    },

    verifyForm() {
      var bool = true;
      this.$refs['main-form'].validate((valid) => bool = valid);
      return bool;
    },

    async submit() {

      if (!this.verifyForm()) return false;
      if (this.mainQuery.level == 2 && !this.mainQuery.parentId) {
        this.$message({ message: '请选择销售上级', type: 'error' });
        return;
      }

      this.loading = true;

      try {
        this.id ? await this.submitSet() : await this.submitAdd();
      } catch (err) { }

      this.loading = false;
    },

    async submitAdd() {
      await ApiMain.add(this.mainQuery);
      this.$message({ message: '添加成功', type: 'success' });
      this.close();
    },

    async submitSet() {

      var req = Object.copy(this.mainQuery);

      req.id = this.id;

      if (!this.resetPassword) {
        delete req.password;
        delete req.password_confirmation;
      }

      let resp = await ApiMain.set(req);
      if (resp.isMe) {
        this.$message({ message: '修改成功，将重新登录', type: 'success' });
        this.logout();
      } else {
        this.$message({ message: '修改成功', type: 'success' });
        this.close();
      }
    },

    copyData(ref, val) {
      this.$refs[ref].select()
      document.execCommand('copy');
      this.$message({ message: '已复制', type: 'success' });
    },

  }
}
</script>

<style>
</style>
